

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=auto>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/img/fluid.png">
  <link rel="icon" href="/img/fluid.png">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
    <meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="author" content="dayu">
  <meta name="keywords" content="">
  
    <meta name="description" content="Vue3声明式渲染reactive() 只适用于对象 (包括数组和内置类型，如 Map 和 Set)。而另一个 API ref() 则可以接受任何值类型。 12345678import &amp;#123; reactive &amp;#125; from &amp;#x27;vue&amp;#x27;const counter &#x3D; reactive(&amp;#123;  count: 0&amp;#125;)console.log(coun">
<meta property="og:type" content="article">
<meta property="og:title" content="vue3">
<meta property="og:url" content="http://dayu.com/2023/02/25/vue3/index.html">
<meta property="og:site_name" content="Dayu">
<meta property="og:description" content="Vue3声明式渲染reactive() 只适用于对象 (包括数组和内置类型，如 Map 和 Set)。而另一个 API ref() 则可以接受任何值类型。 12345678import &amp;#123; reactive &amp;#125; from &amp;#x27;vue&amp;#x27;const counter &#x3D; reactive(&amp;#123;  count: 0&amp;#125;)console.log(coun">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2023-02-24T16:41:04.000Z">
<meta property="article:modified_time" content="2023-09-13T02:33:44.925Z">
<meta property="article:author" content="dayu">
<meta property="article:tag" content="vue3">
<meta name="twitter:card" content="summary_large_image">
  
  
    <meta name="referrer" content="no-referrer-when-downgrade">
  
  
  <title>vue3 - Dayu</title>

  <link  rel="stylesheet" href="https://lib.baomitu.com/twitter-bootstrap/4.6.1/css/bootstrap.min.css" />



  <link  rel="stylesheet" href="https://lib.baomitu.com/github-markdown-css/4.0.0/github-markdown.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/hint.css/2.7.0/hint.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.css" />



<!-- 主题依赖的图标库，不要自行修改 -->
<!-- Do not modify the link that theme dependent icons -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_hj8rtnfg7um.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_lbnruvf0jn.css">


<link  rel="stylesheet" href="/css/main.css" />


  <link id="highlight-css" rel="stylesheet" href="/css/highlight.css" />
  
    <link id="highlight-css-dark" rel="stylesheet" href="/css/highlight-dark.css" />
  



  
<link rel="stylesheet" href="//at.alicdn.com/t/c/font_3846514_kabxni94auf.css">
<link rel="stylesheet" href="//cdn.jsdelivr.net/gh/bynotes/texiao/source/css/shubiao.css">
<link rel="stylesheet" href="//cdn.jsdelivr.net/gh/bynotes/texiao/source/css/gundongtiao.css">



  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    Fluid.ctx = Object.assign({}, Fluid.ctx)
    var CONFIG = {"hostname":"dayu.com","root":"/","version":"1.9.3","typing":{"enable":true,"typeSpeed":70,"cursorChar":"_","loop":false,"scope":[]},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"left","visible":"hover","icon":""},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"code_language":{"enable":true,"default":"TEXT"},"copy_btn":true,"image_caption":{"enable":true},"image_zoom":{"enable":true,"img_url_replace":["",""]},"toc":{"enable":true,"placement":"right","headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":0},"lazyload":{"enable":true,"loading_img":"/img/loading.gif","onlypost":false,"offset_factor":2},"web_analytics":{"enable":true,"follow_dnt":true,"baidu":null,"google":null,"gtag":null,"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":null,"app_key":null,"server_url":null,"path":"window.location.pathname","ignore_local":false}},"search_path":"/local-search.xml"};

    if (CONFIG.web_analytics.follow_dnt) {
      var dntVal = navigator.doNotTrack || window.doNotTrack || navigator.msDoNotTrack;
      Fluid.ctx.dnt = dntVal && (dntVal.startsWith('1') || dntVal.startsWith('yes') || dntVal.startsWith('on'));
    }
  </script>
  <script  src="/js/utils.js" ></script>
  <script  src="/js/color-schema.js" ></script>
  

  

  

  

  

  

  

  



  
<meta name="generator" content="Hexo 5.4.2"></head>


<body>
  

  <header>
    

<div class="header-inner" style="height: 70vh;">
  <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand" href="/">
      <strong>Dayu</strong>
    </a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/">
                <i class="iconfont icon-home-fill"></i>
                首页
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/archives">
                <i class="iconfont icon-books"></i>
                归档
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/categories">
                <i class="iconfont icon-th-large"></i>
                分类
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/tags/">
                <i class="iconfont icon-tags-fill"></i>
                标签
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/about/">
                <i class="iconfont icon-user-fill"></i>
                关于
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/links/">
                <i class="iconfont icon-link-fill"></i>
                友链
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item dropdown">
              <a class="nav-link dropdown-toggle" target="_self" href="javascript:;" role="button"
                 data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                <i class="iconfont icon-book"></i>
                文档
              </a>
              <div class="dropdown-menu" aria-labelledby="navbarDropdown">
                
                  
                  
                  
                  <a class="dropdown-item" target="_blank" rel="noopener" href="https://hexo.fluid-dev.com/">
                    
                    主题博客
                  </a>
                
                  
                  
                  
                  <a class="dropdown-item" target="_blank" rel="noopener" href="https://hexo.fluid-dev.com/docs/guide/">
                    
                    配置指南
                  </a>
                
                  
                  
                  
                  <a class="dropdown-item" target="_blank" rel="noopener" href="https://hexo.fluid-dev.com/docs/icon/">
                    
                    图标用法
                  </a>
                
              </div>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" target="_self" href="javascript:;" data-toggle="modal" data-target="#modalSearch" aria-label="Search">
              &nbsp;<i class="iconfont icon-search"></i>&nbsp;
            </a>
          </li>
          
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" target="_self" href="javascript:;" aria-label="Color Toggle">&nbsp;<i
                class="iconfont icon-dark" id="color-toggle-icon"></i>&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

  

<div id="banner" class="banner" parallax=true
     style="background: url('/img/default.png') no-repeat center center; background-size: cover;">
  <div class="full-bg-img">
    <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
      <div class="banner-text text-center fade-in-up">
        <div class="h2">
          
            <span id="subtitle" data-typed-text="vue3"></span>
          
        </div>

        
          
  <div class="mt-3">
    
      <span class="post-meta mr-2">
        <i class="iconfont icon-author" aria-hidden="true"></i>
        dayu
      </span>
    
    
      <span class="post-meta">
        <i class="iconfont icon-date-fill" aria-hidden="true"></i>
        <time datetime="2023-02-25 00:41" pubdate>
           2023 年 02 月 25 日 , 凌晨 12:41 , 星期六
        </time>
      </span>
    
  </div>

  <div class="mt-1">
    
      <span class="post-meta mr-2">
        <i class="iconfont icon-chart"></i>
        
          <!-- compatible with older versions-->
          11k 字
        
      </span>
    

    
      <span class="post-meta mr-2">
        <i class="iconfont icon-clock-fill"></i>
        
        
        
          <!-- compatible with older versions-->
          89 分钟
        
      </span>
    

    
    
  </div>


        
      </div>

      
    </div>
  </div>
</div>

</div>

  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="side-col d-none d-lg-block col-lg-2">
      

    </div>

    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div id="board">
          <article class="post-content mx-auto">
            <!-- SEO header -->
            <h1 style="display: none">vue3</h1>
            
            
              <div class="markdown-body">
                
                <h1 id="Vue3"><a href="#Vue3" class="headerlink" title="Vue3"></a>Vue3</h1><h2 id="声明式渲染"><a href="#声明式渲染" class="headerlink" title="声明式渲染"></a>声明式渲染</h2><p><code>reactive()</code> 只适用于对象 (包括数组和内置类型，如 <code>Map</code> 和 <code>Set</code>)。而另一个 API <code>ref()</code> 则可以接受任何值类型。</p>
<figure class="highlight axapta"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><code class="hljs axapta">import &#123; reactive &#125; <span class="hljs-keyword">from</span> <span class="hljs-string">&#x27;vue&#x27;</span><br><br><span class="hljs-keyword">const</span> counter = reactive(&#123;<br>  <span class="hljs-keyword">count</span>: <span class="hljs-number">0</span><br>&#125;)<br><br>console.log(counter.<span class="hljs-keyword">count</span>) <span class="hljs-comment">// 0</span><br>counter.<span class="hljs-keyword">count</span>++<br></code></pre></td></tr></table></figure>

<p><code>ref</code> 会返回一个包裹对象，并在 <code>.value</code> 属性下暴露内部值。</p>
<figure class="highlight pgsql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs pgsql"><span class="hljs-keyword">import</span> &#123; <span class="hljs-keyword">ref</span> &#125; <span class="hljs-keyword">from</span> <span class="hljs-string">&#x27;vue&#x27;</span><br><br>const message = <span class="hljs-keyword">ref</span>(<span class="hljs-string">&#x27;Hello World!&#x27;</span>)<br><br>console.log(message.<span class="hljs-keyword">value</span>) // &quot;Hello World!&quot;<br>message.<span class="hljs-keyword">value</span> = <span class="hljs-string">&#x27;Changed&#x27;</span><br></code></pre></td></tr></table></figure>

<p>在组件的 <code>&lt;script setup&gt;</code> 块中声明的响应式状态，可以直接在模板中使用。</p>
<figure class="highlight handlebars"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><code class="hljs handlebars"><span class="language-xml"><span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span></span><span class="hljs-template-variable">&#123;&#123; <span class="hljs-name">message</span> &#125;&#125;</span><span class="language-xml"><span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span></span><br><span class="language-xml"><span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>count is: </span><span class="hljs-template-variable">&#123;&#123; <span class="hljs-name">counter.count</span> &#125;&#125;</span><span class="language-xml"><span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span></span><br></code></pre></td></tr></table></figure>

<p>注意我们在模板中访问的 <code>message</code> ref 时不需要使用 <code>.value</code>：它会被自动解包，让使用更简单。</p>
<p>在双花括号中的内容并不只限于标识符或路径——我们可以使用任何有效的 JavaScript 表达式。</p>
<figure class="highlight handlebars"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs handlebars"><span class="language-xml"><span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span></span><span class="hljs-template-variable">&#123;&#123; <span class="hljs-name">message.split</span>(<span class="hljs-name">&#x27;&#x27;</span>).reverse().join(<span class="hljs-name">&#x27;&#x27;</span>) &#125;&#125;</span><span class="language-xml"><span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span></span><br></code></pre></td></tr></table></figure>

<blockquote>
<p>现在，试着自己创建一些响应式状态，用它来为模板中的 `` 渲染动态的文本内容。</p>
</blockquote>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><code class="hljs vue">&lt;script setup&gt;<br>import &#123; reactive, ref &#125; from &#x27;vue&#x27;<br><br>const counter = reactive(&#123; count: 0 &#125;)<br>const message = ref(&#x27;Hello World!&#x27;)<br>&lt;/script&gt;<br><br>&lt;template&gt;<br>  &lt;h1&gt;&#123;&#123; message &#125;&#125;&lt;/h1&gt;<br>  &lt;p&gt;Count is: &#123;&#123; counter.count &#125;&#125;&lt;/p&gt;<br>&lt;/template&gt;<br></code></pre></td></tr></table></figure>

<p>##Attribute 绑定</p>
<p>在 Vue 中，mustache 语法 (即双大括号) 只能用于文本插值。为了给 attribute 绑定一个动态值，需要使用 <code>v-bind</code> 指令：</p>
<figure class="highlight applescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs applescript">&lt;<span class="hljs-keyword">div</span> v-bind:<span class="hljs-built_in">id</span>=<span class="hljs-string">&quot;dynamicId&quot;</span>&gt;&lt;/<span class="hljs-keyword">div</span>&gt;<br></code></pre></td></tr></table></figure>

<p>由于 <code>v-bind</code> 使用地非常频繁，它有一个专门的简写语法：</p>
<figure class="highlight elixir"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs elixir">&lt;div <span class="hljs-symbol">:id=<span class="hljs-string">&quot;dynamicId&quot;</span>&gt;&lt;/div&gt;</span><br></code></pre></td></tr></table></figure>

<blockquote>
<p>现在，试着把一个动态的 <code>class</code> 绑定添加到这个<code>&lt;h1&gt;</code>上，并使用 <code>titleClass</code> 的 ref 作为它的值。如果绑定正确，文字将会变为红色。</p>
</blockquote>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><code class="hljs vue">&lt;script setup&gt;<br>import &#123; ref &#125; from &#x27;vue&#x27;<br><br>const titleClass = ref(&#x27;title&#x27;)<br>&lt;/script&gt;<br><br>&lt;template&gt;<br>  &lt;h1 :class=&quot;titleClass&quot;&gt;Make me red&lt;/h1&gt;<br>&lt;/template&gt;<br><br>&lt;style&gt;<br>.title &#123;<br>  color: red;<br>&#125;<br>&lt;/style&gt;<br></code></pre></td></tr></table></figure>

<h2 id="事件监听"><a href="#事件监听" class="headerlink" title="事件监听"></a>事件监听</h2><p>我们可以使用 <code>v-on</code> 指令监听 DOM 事件：</p>
<figure class="highlight handlebars"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs handlebars"><span class="language-xml"><span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">v-on:click</span>=<span class="hljs-string">&quot;increment&quot;</span>&gt;</span></span><span class="hljs-template-variable">&#123;&#123; <span class="hljs-name">count</span> &#125;&#125;</span><span class="language-xml"><span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span></span><br></code></pre></td></tr></table></figure>

<p>因为其经常使用，<code>v-on</code> 也有一个简写语法：</p>
<figure class="highlight handlebars"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs handlebars"><span class="language-xml"><span class="hljs-tag">&lt;<span class="hljs-name">button</span> @<span class="hljs-attr">click</span>=<span class="hljs-string">&quot;increment&quot;</span>&gt;</span></span><span class="hljs-template-variable">&#123;&#123; <span class="hljs-name">count</span> &#125;&#125;</span><span class="language-xml"><span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span></span><br></code></pre></td></tr></table></figure>

<p>此处，<code>increment</code> 引用了一个在 <code>&lt;script setup&gt;</code> 中声明的函数：</p>
<figure class="highlight dust"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><code class="hljs dust"><span class="language-xml"><span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">setup</span>&gt;</span><span class="language-javascript"></span></span><br><span class="language-javascript"><span class="language-xml"><span class="hljs-keyword">import</span> </span></span><span class="hljs-template-variable">&#123; ref &#125;</span><span class="language-xml"><span class="language-javascript"> <span class="hljs-keyword">from</span> <span class="hljs-string">&#x27;vue&#x27;</span></span></span><br><span class="language-javascript"><span class="language-xml"></span></span><br><span class="language-javascript"><span class="language-xml"><span class="hljs-keyword">const</span> count = <span class="hljs-title function_">ref</span>(<span class="hljs-number">0</span>)</span></span><br><span class="language-javascript"><span class="language-xml"></span></span><br><span class="language-javascript"><span class="language-xml"><span class="hljs-keyword">function</span> <span class="hljs-title function_">increment</span>(<span class="hljs-params"></span>) </span></span><span class="hljs-template-variable">&#123;</span><br><span class="hljs-template-variable">  // 更新组件状态</span><br><span class="hljs-template-variable">  count.value++</span><br><span class="hljs-template-variable">&#125;</span><span class="language-xml"></span><br><span class="language-xml"><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span></span><br></code></pre></td></tr></table></figure>

<p>现在，尝试自行实现 <code>increment</code> 函数并通过使用 <code>v-on</code> 将其绑定到按钮上。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><code class="hljs vue">&lt;script setup&gt;<br>import &#123; ref &#125; from &#x27;vue&#x27;<br><br>const count = ref(0)<br><br>function increment() &#123;<br>  count.value++<br>&#125;<br>&lt;/script&gt;<br><br>&lt;template&gt;<br>  &lt;button @click=&quot;increment&quot;&gt;count is: &#123;&#123; count &#125;&#125;&lt;/button&gt;<br>&lt;/template&gt;<br></code></pre></td></tr></table></figure>

<h2 id="表单绑定"><a href="#表单绑定" class="headerlink" title="表单绑定"></a>表单绑定</h2><p>我们可以同时使用 <code>v-bind</code> 和 <code>v-on</code> 来在表单的输入元素上创建双向绑定：</p>
<figure class="highlight routeros"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs routeros">&lt;input :<span class="hljs-attribute">value</span>=<span class="hljs-string">&quot;text&quot;</span> @<span class="hljs-attribute">input</span>=<span class="hljs-string">&quot;onInput&quot;</span>&gt;<br></code></pre></td></tr></table></figure>

<figure class="highlight stylus"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs stylus">function <span class="hljs-built_in">onInput</span>(e) &#123;<br>  <span class="hljs-comment">// v-on 处理函数会接收原生 DOM 事件</span><br>  <span class="hljs-comment">// 作为其参数。</span><br>  text<span class="hljs-selector-class">.value</span> = e<span class="hljs-selector-class">.target</span><span class="hljs-selector-class">.value</span><br>&#125;<br></code></pre></td></tr></table></figure>

<p>为了简化双向绑定，Vue 提供了一个 <code>v-model</code> 指令，它实际上是上述操作的语法糖：</p>
<figure class="highlight routeros"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs routeros">&lt;input <span class="hljs-attribute">v-model</span>=<span class="hljs-string">&quot;text&quot;</span>&gt;<br></code></pre></td></tr></table></figure>

<p><code>v-model</code> 会将被绑定的值与 `` 的值自动同步，这样我们就不必再使用事件处理函数了。</p>
<p><code>v-model</code> 不仅支持文本输入框，也支持诸如多选框、单选框、下拉框之类的输入类型。</p>
<blockquote>
<p>现在，试着用 <code>v-model</code> 把代码重构一下吧。</p>
</blockquote>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><code class="hljs vue">&lt;script setup&gt;<br>import &#123; ref &#125; from &#x27;vue&#x27;<br><br>const text = ref(&#x27;&#x27;)<br>&lt;/script&gt;<br><br>&lt;template&gt;<br>  &lt;input v-model=&quot;text&quot; placeholder=&quot;Type here&quot;&gt;<br>  &lt;p&gt;&#123;&#123; text &#125;&#125;&lt;/p&gt;<br>&lt;/template&gt;<br></code></pre></td></tr></table></figure>

<h2 id="条件渲染"><a href="#条件渲染" class="headerlink" title="条件渲染"></a>条件渲染</h2><p>我们可以使用 <code>v-if</code> 指令来有条件地渲染元素：</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs xml"><span class="hljs-tag">&lt;<span class="hljs-name">h1</span> <span class="hljs-attr">v-if</span>=<span class="hljs-string">&quot;awesome&quot;</span>&gt;</span>Vue is awesome!<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span><br></code></pre></td></tr></table></figure>

<p>我们也可以使用 <code>v-else</code> 和 <code>v-else-if</code> 来表示其他的条件分支：</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><code class="hljs xml"><span class="hljs-tag">&lt;<span class="hljs-name">h1</span> <span class="hljs-attr">v-if</span>=<span class="hljs-string">&quot;awesome&quot;</span>&gt;</span>Vue is awesome!<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span><br><span class="hljs-tag">&lt;<span class="hljs-name">h1</span> <span class="hljs-attr">v-else</span>&gt;</span>Oh no 😢<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span><br></code></pre></td></tr></table></figure>

<p>现在，示例程序同时展示了两个 <code>&lt;h1&gt;</code> 标签，并且按钮不执行任何操作。尝试给它们添加 <code>v-if</code> 和 <code>v-else</code> 指令，并实现 <code>toggle()</code> 方法，让我们可以使用按钮在它们之间切换。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><code class="hljs vue">&lt;script setup&gt;<br>import &#123; ref &#125; from &#x27;vue&#x27;<br><br>const awesome = ref(true)<br><br>function toggle() &#123;<br>  awesome.value = !awesome.value<br>&#125;<br>&lt;/script&gt;<br><br>&lt;template&gt;<br>  &lt;button @click=&quot;toggle&quot;&gt;toggle&lt;/button&gt;<br>  &lt;h1 v-if=&quot;awesome&quot;&gt;Vue is awesome!&lt;/h1&gt;<br>  &lt;h1 v-else&gt;Oh no 😢&lt;/h1&gt;<br>&lt;/template&gt;<br></code></pre></td></tr></table></figure>

<h2 id="列表渲染"><a href="#列表渲染" class="headerlink" title="列表渲染"></a>列表渲染</h2><p>我们可以使用 <code>v-for</code> 指令来渲染一个基于源数组的列表：</p>
<figure class="highlight handlebars"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs handlebars"><span class="language-xml"><span class="hljs-tag">&lt;<span class="hljs-name">ul</span>&gt;</span></span><br><span class="language-xml">  <span class="hljs-tag">&lt;<span class="hljs-name">li</span> <span class="hljs-attr">v-for</span>=<span class="hljs-string">&quot;todo in todos&quot;</span> <span class="hljs-attr">:key</span>=<span class="hljs-string">&quot;todo.id&quot;</span>&gt;</span></span><br><span class="language-xml">    </span><span class="hljs-template-variable">&#123;&#123; <span class="hljs-name">todo.text</span> &#125;&#125;</span><span class="language-xml"></span><br><span class="language-xml">  <span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span></span><br><span class="language-xml"><span class="hljs-tag">&lt;/<span class="hljs-name">ul</span>&gt;</span></span><br></code></pre></td></tr></table></figure>

<p>这里的 <code>todo</code> 是一个局部变量，表示当前正在迭代的数组元素。它只能在 <code>v-for</code> 所绑定的元素上或是其内部访问，就像函数的作用域一样。</p>
<p>注意，我们还给每个 todo 对象设置了唯一的 <code>id</code>，并且将它作为特殊的 <code>key</code> <code>attribute</code> 绑定到每个 <code>&lt;li&gt;</code>。<code>key</code> 使得 Vue 能够精确的移动每个 <code>&lt;li&gt;</code>，以匹配对应的对象在数组中的位置。</p>
<p>更新列表有两种方式：</p>
<ol>
<li><p>在源数组上调用变更方法：</p>
<figure class="highlight haxe"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs haxe">todos.value.push(<span class="hljs-keyword">new</span><span class="hljs-type">Todo</span>)<br></code></pre></td></tr></table></figure></li>
<li><p>使用新的数组替代原数组：</p>
<figure class="highlight stylus"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs stylus">todos<span class="hljs-selector-class">.value</span> = todos<span class="hljs-selector-class">.value</span><span class="hljs-selector-class">.filter</span>(<span class="hljs-comment">/* ... */</span>)<br></code></pre></td></tr></table></figure></li>
</ol>
<p>这里有一个简单的 todo 列表——试着实现一下 <code>addTodo()</code> 和 <code>removeTodo()</code> 这两个方法的逻辑，使列表能够正常工作！</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br></pre></td><td class="code"><pre><code class="hljs vue">&lt;script setup&gt;<br>import &#123; ref &#125; from &#x27;vue&#x27;<br><br>// 给每个 todo 对象一个唯一的 id<br>let id = 0<br><br>const newTodo = ref(&#x27;&#x27;)<br>const todos = ref([<br>  &#123; id: id++, text: &#x27;Learn HTML&#x27; &#125;,<br>  &#123; id: id++, text: &#x27;Learn JavaScript&#x27; &#125;,<br>  &#123; id: id++, text: &#x27;Learn Vue&#x27; &#125;<br>])<br><br>function addTodo() &#123;<br>  todos.value.push(&#123; id: id++, text: newTodo.value &#125;)<br>  newTodo.value = &#x27;&#x27;<br>&#125;<br><br>function removeTodo(todo) &#123;<br>  todos.value = todos.value.filter((t) =&gt; t !== todo)<br>&#125;<br>&lt;/script&gt;<br><br>&lt;template&gt;<br>  &lt;form @submit.prevent=&quot;addTodo&quot;&gt;<br>    &lt;input v-model=&quot;newTodo&quot;&gt;<br>    &lt;button&gt;Add Todo&lt;/button&gt;    <br>  &lt;/form&gt;<br>  &lt;ul&gt;<br>    &lt;li v-for=&quot;todo in todos&quot; :key=&quot;todo.id&quot;&gt;<br>      &#123;&#123; todo.text &#125;&#125;<br>      &lt;button @click=&quot;removeTodo(todo)&quot;&gt;X&lt;/button&gt;<br>    &lt;/li&gt;<br>  &lt;/ul&gt;<br>&lt;/template&gt;<br></code></pre></td></tr></table></figure>

<h2 id="计算属性"><a href="#计算属性" class="headerlink" title="计算属性"></a>计算属性</h2><p><code>computed()</code>。它可以让我们创建一个计算属性 ref，这个 ref 会动态地根据其他响应式数据源来计算其 <code>.value</code>：</p>
<figure class="highlight angelscript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><code class="hljs angelscript"><span class="hljs-keyword">import</span> &#123; <span class="hljs-built_in">ref</span>, computed &#125; <span class="hljs-keyword">from</span> <span class="hljs-string">&#x27;vue&#x27;</span><br><br><span class="hljs-keyword">const</span> hideCompleted = <span class="hljs-built_in">ref</span>(<span class="hljs-literal">false</span>)<br><span class="hljs-keyword">const</span> todos = <span class="hljs-built_in">ref</span>([<br>  <span class="hljs-comment">/* ... */</span><br>])<br><br><span class="hljs-keyword">const</span> filteredTodos = computed(() =&gt; &#123;<br>  <span class="hljs-comment">// 根据 `todos.value` &amp; `hideCompleted.value`</span><br>  <span class="hljs-comment">// 返回过滤后的 todo 项目</span><br>&#125;)<br></code></pre></td></tr></table></figure>

<figure class="highlight routeros"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><code class="hljs routeros">- &lt;li <span class="hljs-attribute">v-for</span>=<span class="hljs-string">&quot;todo in todos&quot;</span>&gt;<br>+ &lt;li <span class="hljs-attribute">v-for</span>=<span class="hljs-string">&quot;todo in filteredTodos&quot;</span>&gt;<br></code></pre></td></tr></table></figure>

<p>计算属性会自动跟踪其计算中所使用的到的其他响应式状态，并将它们收集为自己的依赖。计算结果会被缓存，并只有在其依赖发生改变时才会被自动更新。</p>
<p>现在，试着添加 <code>filteredTodos</code> 计算属性并实现计算逻辑！如果实现正确，在隐藏已完成项目的状态下勾选一个 todo，它也应当被立即隐藏。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br></pre></td><td class="code"><pre><code class="hljs vue">&lt;script setup&gt;<br>import &#123; ref, computed &#125; from &#x27;vue&#x27;<br><br>let id = 0<br><br>const newTodo = ref(&#x27;&#x27;)<br>const hideCompleted = ref(false)<br>const todos = ref([<br>  &#123; id: id++, text: &#x27;Learn HTML&#x27;, done: true &#125;,<br>  &#123; id: id++, text: &#x27;Learn JavaScript&#x27;, done: true &#125;,<br>  &#123; id: id++, text: &#x27;Learn Vue&#x27;, done: false &#125;<br>])<br><br>const filteredTodos = computed(() =&gt; &#123;<br>  return hideCompleted.value<br>    ? todos.value.filter((t) =&gt; !t.done)<br>    : todos.value<br>&#125;)<br><br>function addTodo() &#123;<br>  todos.value.push(&#123; id: id++, text: newTodo.value, done: false &#125;)<br>  newTodo.value = &#x27;&#x27;<br>&#125;<br><br>function removeTodo(todo) &#123;<br>  todos.value = todos.value.filter((t) =&gt; t !== todo)<br>&#125;<br>&lt;/script&gt;<br><br>&lt;template&gt;<br>  &lt;form @submit.prevent=&quot;addTodo&quot;&gt;<br>    &lt;input v-model=&quot;newTodo&quot;&gt;<br>    &lt;button&gt;Add Todo&lt;/button&gt;<br>  &lt;/form&gt;<br>  &lt;ul&gt;<br>    &lt;li v-for=&quot;todo in filteredTodos&quot; :key=&quot;todo.id&quot;&gt;<br>      &lt;input type=&quot;checkbox&quot; v-model=&quot;todo.done&quot;&gt;<br>      &lt;span :class=&quot;&#123; done: todo.done &#125;&quot;&gt;&#123;&#123; todo.text &#125;&#125;&lt;/span&gt;<br>      &lt;button @click=&quot;removeTodo(todo)&quot;&gt;X&lt;/button&gt;<br>    &lt;/li&gt;<br>  &lt;/ul&gt;<br>  &lt;button @click=&quot;hideCompleted = !hideCompleted&quot;&gt;<br>    &#123;&#123; hideCompleted ? &#x27;Show all&#x27; : &#x27;Hide completed&#x27; &#125;&#125;<br>  &lt;/button&gt;<br>&lt;/template&gt;<br><br>&lt;style&gt;<br>.done &#123;<br>  text-decoration: line-through;<br>&#125;<br>&lt;/style&gt;<br></code></pre></td></tr></table></figure>

<h2 id="生命周期和模板引用"><a href="#生命周期和模板引用" class="headerlink" title="生命周期和模板引用"></a>生命周期和模板引用</h2><p>目前为止，Vue 为我们处理了所有的 DOM 更新，这要归功于响应性和声明式渲染。然而，有时我们也会不可避免地需要手动操作 DOM。</p>
<p>这时我们需要使用<strong>模板引用</strong>——也就是指向模板中一个 DOM 元素的 ref。我们需要通过这个特殊的 <code>ref</code> attribute 来实现模板引用：</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs xml"><span class="hljs-tag">&lt;<span class="hljs-name">p</span> <span class="hljs-attr">ref</span>=<span class="hljs-string">&quot;p&quot;</span>&gt;</span>hello<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span><br></code></pre></td></tr></table></figure>

<p>要访问该引用，我们需要声明一个同名的 ref：</p>
<figure class="highlight angelscript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs angelscript"><span class="hljs-keyword">const</span> p = <span class="hljs-built_in">ref</span>(<span class="hljs-literal">null</span>)<br></code></pre></td></tr></table></figure>

<p>注意这个 ref 使用 <code>null</code> 值来初始化。这是因为当 <code>&lt;script setup&gt;</code> 执行时，DOM 元素还不存在。模板引用 ref 只能在组件<strong>挂载</strong>后访问。</p>
<p>要在挂载之后执行代码，我们可以使用 <code>onMounted()</code> 函数：</p>
<figure class="highlight coffeescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs coffeescript"><span class="hljs-keyword">import</span> &#123; onMounted &#125; <span class="hljs-keyword">from</span> <span class="hljs-string">&#x27;vue&#x27;</span><br><br>onMounted(<span class="hljs-function"><span class="hljs-params">()</span> =&gt;</span> &#123;<br>  <span class="hljs-regexp">//</span> 此时组件已经挂载。<br>&#125;)<br></code></pre></td></tr></table></figure>

<p>这被称为<strong>生命周期钩子</strong>——它允许我们注册一个在组件的特定生命周期调用的回调函数。还有一些其他的钩子如 <code>onUpdated</code> 和 <code>onUnmounted</code>。更多细节请查阅<a target="_blank" rel="noopener" href="https://cn.vuejs.org/guide/essentials/lifecycle.html#lifecycle-diagram">生命周期图示</a>。</p>
<p>现在，尝试添加一个 <code>onMounted</code> 钩子，然后通过 <code>p.value</code> 访问 <code>&lt;p&gt;</code>，并直接对其执行一些 DOM 操作。(例如修改它的 <code>textContent</code>)。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><code class="hljs vue">&lt;script setup&gt;<br>import &#123; ref, onMounted &#125; from &#x27;vue&#x27;<br><br>const p = ref(null)<br><br>onMounted(() =&gt; &#123;<br>  p.value.textContent = &#x27;mounted!&#x27;<br>&#125;)<br>&lt;/script&gt;<br><br>&lt;template&gt;<br>  &lt;p ref=&quot;p&quot;&gt;hello&lt;/p&gt;<br>&lt;/template&gt;<br></code></pre></td></tr></table></figure>

<h2 id="侦听器"><a href="#侦听器" class="headerlink" title="侦听器"></a>侦听器</h2><p>有时我们需要响应性地执行一些“副作用”——例如，当一个数字改变时将其输出到控制台。我们可以通过侦听器来实现它：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><code class="hljs javascript"><span class="hljs-keyword">import</span> &#123; ref, watch &#125; <span class="hljs-keyword">from</span> <span class="hljs-string">&#x27;vue&#x27;</span><br><br><span class="hljs-keyword">const</span> count = <span class="hljs-title function_">ref</span>(<span class="hljs-number">0</span>)<br><br><span class="hljs-title function_">watch</span>(count, <span class="hljs-function">(<span class="hljs-params">newCount</span>) =&gt;</span> &#123;<br>  <span class="hljs-comment">// 没错，console.log() 是一个副作用</span><br>  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">`new count is: <span class="hljs-subst">$&#123;newCount&#125;</span>`</span>)<br>&#125;)<br></code></pre></td></tr></table></figure>

<p><code>watch()</code> 可以直接侦听一个 ref，并且只要 <code>count</code> 的值改变就会触发回调。<code>watch()</code> 也可以侦听其他类型的数据源——更多详情请参阅<a target="_blank" rel="noopener" href="https://cn.vuejs.org/guide/essentials/watchers.html">指南 - 侦听器</a>。</p>
<p>一个比在控制台输出更加实际的例子是当 ID 改变时抓取新的数据。在右边的例子中就是这样一个组件。该组件被挂载时，会从模拟 API 中抓取 todo 数据，同时还有一个按钮可以改变要抓取的 todo 的 ID。现在，尝试实现一个侦听器，使得组件能够在按钮被点击时抓取新的 todo 项目。</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><code class="hljs vue">&lt;script setup&gt;<br>import &#123; ref, watch &#125; from &#x27;vue&#x27;<br><br>const todoId = ref(1)<br>const todoData = ref(null)<br><br>async function fetchData() &#123;<br>  todoData.value = null<br>  const res = await fetch(<br>    `https://jsonplaceholder.typicode.com/todos/$&#123;todoId.value&#125;`<br>  )<br>  todoData.value = await res.json()<br>&#125;<br><br>fetchData()<br><br>watch(todoId, fetchData)<br>&lt;/script&gt;<br><br>&lt;template&gt;<br>  &lt;p&gt;Todo id: &#123;&#123; todoId &#125;&#125;&lt;/p&gt;<br>  &lt;button @click=&quot;todoId++&quot;&gt;Fetch next todo&lt;/button&gt;<br>  &lt;p v-if=&quot;!todoData&quot;&gt;Loading...&lt;/p&gt;<br>  &lt;pre v-else&gt;&#123;&#123; todoData &#125;&#125;&lt;/pre&gt;<br>&lt;/template&gt;<br></code></pre></td></tr></table></figure>

<h2 id="组件"><a href="#组件" class="headerlink" title="组件"></a>组件</h2><p>父组件可以在模板中渲染另一个组件作为子组件。要使用子组件，我们需要先导入它：</p>
<figure class="highlight clean"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs clean"><span class="hljs-keyword">import</span> ChildComp <span class="hljs-keyword">from</span> <span class="hljs-string">&#x27;./ChildComp.vue&#x27;</span><br></code></pre></td></tr></table></figure>

<p>然后我们就可以在模板中使用组件，就像这样：</p>
<figure class="highlight apache"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs apache"><span class="hljs-section">&lt;ChildComp /&gt;</span><br></code></pre></td></tr></table></figure>

<h2 id="Props"><a href="#Props" class="headerlink" title="Props"></a>Props</h2><p>子组件可以通过 <strong>props</strong> 从父组件接受动态数据。首先，需要声明它所接受的 props：</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><code class="hljs xml"><span class="hljs-comment">&lt;!-- ChildComp.vue --&gt;</span><br><span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">setup</span>&gt;</span><span class="language-javascript"></span><br><span class="language-javascript"><span class="hljs-keyword">const</span> props = <span class="hljs-title function_">defineProps</span>(&#123;</span><br><span class="language-javascript">  <span class="hljs-attr">msg</span>: <span class="hljs-title class_">String</span></span><br><span class="language-javascript">&#125;)</span><br><span class="language-javascript"></span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span><br></code></pre></td></tr></table></figure>

<p>注意 <code>defineProps()</code> 是一个编译时宏，并不需要导入。一旦声明，<code>msg</code> prop 就可以在子组件的模板中使用。它也可以通过 <code>defineProps()</code> 所返回的对象在 JavaScript 中访问。</p>
<p>父组件可以像声明 HTML attributes 一样传递 props。若要传递动态值，也可以使用 <code>v-bind</code> 语法：</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs xml"><span class="hljs-tag">&lt;<span class="hljs-name">ChildComp</span> <span class="hljs-attr">:msg</span>=<span class="hljs-string">&quot;greeting&quot;</span> /&gt;</span><br></code></pre></td></tr></table></figure>

<h2 id="Emits"><a href="#Emits" class="headerlink" title="Emits"></a>Emits</h2><p>除了接收 props，子组件还可以向父组件触发事件：</p>
<figure class="highlight stylus"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><code class="hljs stylus">&lt;script setup&gt;<br><span class="hljs-comment">// 声明触发的事件</span><br>const emit = <span class="hljs-built_in">defineEmits</span>(<span class="hljs-selector-attr">[<span class="hljs-string">&#x27;response&#x27;</span>]</span>)<br><br><span class="hljs-comment">// 带参数触发</span><br><span class="hljs-function"><span class="hljs-title">emit</span><span class="hljs-params">(<span class="hljs-string">&#x27;response&#x27;</span>, <span class="hljs-string">&#x27;hello from child&#x27;</span>)</span></span><br>&lt;/script&gt;<br></code></pre></td></tr></table></figure>

<p><code>emit()</code> 的第一个参数是事件的名称。其他所有参数都将传递给事件监听器。</p>
<p>父组件可以使用 <code>v-on</code> 监听子组件触发的事件——这里的处理函数接收了子组件触发事件时的额外参数并将它赋值给了本地状态：</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs xml"><span class="hljs-tag">&lt;<span class="hljs-name">ChildComp</span> @<span class="hljs-attr">response</span>=<span class="hljs-string">&quot;(msg) =&gt; childMsg = msg&quot;</span> /&gt;</span><br></code></pre></td></tr></table></figure>

<h2 id="插槽"><a href="#插槽" class="headerlink" title="插槽"></a>插槽</h2><p>除了通过 props 传递数据外，父组件还可以通过<strong>插槽</strong> (slots) 将模板片段传递给子组件：</p>
<figure class="highlight maxima"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs maxima">&lt;ChildComp&gt;<br>  This <span class="hljs-built_in">is</span> <span class="hljs-built_in">some</span> slot <span class="hljs-built_in">content</span>!<br>&lt;/ChildComp&gt;<br></code></pre></td></tr></table></figure>

<p>在子组件中，可以使用 `` 元素作为插槽出口 (slot outlet) 渲染父组件中的插槽内容 (slot content)：</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><code class="hljs xml"><span class="hljs-comment">&lt;!-- 在子组件的模板中 --&gt;</span><br><span class="hljs-tag">&lt;<span class="hljs-name">slot</span>/&gt;</span><br></code></pre></td></tr></table></figure>

<p><code>&lt;slot&gt;</code> 插口中的内容将被当作“默认”内容：它会在父组件没有传递任何插槽内容时显示：</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs xml"><span class="hljs-tag">&lt;<span class="hljs-name">slot</span>&gt;</span>Fallback content<span class="hljs-tag">&lt;/<span class="hljs-name">slot</span>&gt;</span><br></code></pre></td></tr></table></figure>

<p>现在我们没有给 <code>&lt;ChildComp&gt;</code> 传递任何插槽内容，所以你将看到默认内容。让我们利用父组件的 <code>msg</code> 状态为子组件提供一些插槽内容吧。</p>
<p><code>父组件</code></p>
<figure class="highlight handlebars"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><code class="hljs handlebars"><span class="language-xml"><span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">setup</span>&gt;</span><span class="language-javascript"></span></span><br><span class="language-javascript"><span class="language-xml"><span class="hljs-keyword">import</span> &#123; ref &#125; <span class="hljs-keyword">from</span> <span class="hljs-string">&#x27;vue&#x27;</span></span></span><br><span class="language-javascript"><span class="language-xml"><span class="hljs-keyword">import</span> <span class="hljs-title class_">ChildComp</span> <span class="hljs-keyword">from</span> <span class="hljs-string">&#x27;./ChildComp.vue&#x27;</span></span></span><br><span class="language-javascript"><span class="language-xml"></span></span><br><span class="language-javascript"><span class="language-xml"><span class="hljs-keyword">const</span> msg = <span class="hljs-title function_">ref</span>(<span class="hljs-string">&#x27;from parent&#x27;</span>)</span></span><br><span class="language-javascript"><span class="language-xml"></span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span></span><br><span class="language-xml"></span><br><span class="language-xml"><span class="hljs-tag">&lt;<span class="hljs-name">template</span>&gt;</span></span><br><span class="language-xml">  <span class="hljs-tag">&lt;<span class="hljs-name">ChildComp</span>&gt;</span>Message: </span><span class="hljs-template-variable">&#123;&#123; <span class="hljs-name">msg</span> &#125;&#125;</span><span class="language-xml"><span class="hljs-tag">&lt;/<span class="hljs-name">ChildComp</span>&gt;</span></span><br><span class="language-xml"><span class="hljs-tag">&lt;/<span class="hljs-name">template</span>&gt;</span></span><br></code></pre></td></tr></table></figure>

<p><code>子组件</code></p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs xml"><span class="hljs-tag">&lt;<span class="hljs-name">template</span>&gt;</span><br>  <span class="hljs-tag">&lt;<span class="hljs-name">slot</span>&gt;</span>Fallback content<span class="hljs-tag">&lt;/<span class="hljs-name">slot</span>&gt;</span><br><span class="hljs-tag">&lt;/<span class="hljs-name">template</span>&gt;</span><br></code></pre></td></tr></table></figure>


                
              </div>
            
            <hr/>
            <div>
              <div class="post-metas my-3">
  
    <div class="post-meta mr-3 d-flex align-items-center">
      <i class="iconfont icon-category"></i>
      

<span class="category-chains">
  
  
    
      <span class="category-chain">
        
  <a href="/categories/%E5%89%8D%E7%AB%AF/" class="category-chain-item">前端</a>
  
  

      </span>
    
  
</span>

    </div>
  
  
    <div class="post-meta">
      <i class="iconfont icon-tags"></i>
      
        <a href="/tags/vue3/">#vue3</a>
      
    </div>
  
</div>


              
  

  <div class="license-box my-3">
    <div class="license-title">
      <div>vue3</div>
      <div>http://dayu.com/2023/02/25/vue3/</div>
    </div>
    <div class="license-meta">
      
        <div class="license-meta-item">
          <div>作者</div>
          <div>dayu</div>
        </div>
      
      
        <div class="license-meta-item license-meta-date">
          <div>发布于</div>
          <div>2023年2月25日</div>
        </div>
      
      
      
        <div class="license-meta-item">
          <div>许可协议</div>
          <div>
            
              
              
                <a target="_blank" href="https://creativecommons.org/licenses/by/4.0/">
                  <span class="hint--top hint--rounded" aria-label="BY - 署名">
                    <i class="iconfont icon-by"></i>
                  </span>
                </a>
              
            
          </div>
        </div>
      
    </div>
    <div class="license-icon iconfont"></div>
  </div>



              
                <div class="post-prevnext my-3">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/2023/02/25/%E5%89%8D%E7%AB%AF%E7%9F%A5%E8%AF%86%E7%82%B9/" title="前端知识点">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">前端知识点</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/2023/02/25/js%E6%B5%85%E6%8B%B7%E8%B4%9D%E4%B8%8E%E6%B7%B1%E6%8B%B7%E8%B4%9D/" title="js浅拷贝与深拷贝">
                        <span class="hidden-mobile">js浅拷贝与深拷贝</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
  <article id="comments" lazyload>
    
  <div id="valine"></div>
  <script type="text/javascript">
    Fluid.utils.loadComments('#valine', function() {
      Fluid.utils.createScript('https://lib.baomitu.com/valine/1.5.1/Valine.min.js', function() {
        var options = Object.assign(
          {"appId":"你的appId","appKey":"你的appKey","path":"window.location.pathname","placeholder":"留言仅限讨论，禁止广告等行为","avatar":"retro","meta":["nick","mail","link"],"requiredFields":[],"pageSize":10,"lang":"zh-CN","highlight":false,"recordIP":false,"serverURLs":"你的serverURLs","emojiCDN":null,"emojiMaps":null,"enableQQ":false},
          {
            el: "#valine",
            path: window.location.pathname
          }
        )
        new Valine(options);
        Fluid.utils.waitElementVisible('#valine .vcontent', () => {
          var imgSelector = '#valine .vcontent img:not(.vemoji)';
          Fluid.plugins.imageCaption(imgSelector);
          Fluid.plugins.fancyBox(imgSelector);
        })
      });
    });
  </script>
  <noscript>Please enable JavaScript to view the comments</noscript>


  </article>


          </article>
        </div>
      </div>
    </div>

    <div class="side-col d-none d-lg-block col-lg-2">
      
  <aside class="sidebar" style="margin-left: -1rem">
    <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div class="toc-body" id="toc-body"></div>
</div>



  </aside>


    </div>
  </div>
</div>





  



  



  



  



  







    

    
      <a id="scroll-top-button" aria-label="TOP" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v" for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>

    

    
  </main>

  <footer>
    <div class="footer-inner">
  
    <div class="footer-content">
       <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>Hexo</span></a> <i class="iconfont icon-love"></i> <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener"><span>Fluid</span></a> 
    </div>
  
  
    <div class="statistics">
  
  

  
    
      <span id="busuanzi_container_site_pv" style="display: none">
        总访问量 
        <span id="busuanzi_value_site_pv"></span>
         次
      </span>
    
    
      <span id="busuanzi_container_site_uv" style="display: none">
        总访客数 
        <span id="busuanzi_value_site_uv"></span>
         人
      </span>
    
    
  
</div>

  
  
  
</div>

  </footer>

  <!-- Scripts -->
  
  <script  src="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://lib.baomitu.com/jquery/3.6.0/jquery.min.js" ></script>
<script  src="https://lib.baomitu.com/twitter-bootstrap/4.6.1/js/bootstrap.min.js" ></script>
<script  src="/js/events.js" ></script>
<script  src="/js/plugins.js" ></script>


  <script  src="https://lib.baomitu.com/typed.js/2.0.12/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var subtitle = document.getElementById('subtitle');
      if (!subtitle || !typing) {
        return;
      }
      var text = subtitle.getAttribute('data-typed-text');
      
        typing(text);
      
    })(window, document);
  </script>




  
    <script  src="/js/img-lazyload.js" ></script>
  




  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/tocbot/4.18.2/tocbot.min.js', function() {
    var toc = jQuery('#toc');
    if (toc.length === 0 || !window.tocbot) { return; }
    var boardCtn = jQuery('#board-ctn');
    var boardTop = boardCtn.offset().top;

    window.tocbot.init(Object.assign({
      tocSelector     : '#toc-body',
      contentSelector : '.markdown-body',
      linkClass       : 'tocbot-link',
      activeLinkClass : 'tocbot-active-link',
      listClass       : 'tocbot-list',
      isCollapsedClass: 'tocbot-is-collapsed',
      collapsibleClass: 'tocbot-is-collapsible',
      scrollSmooth    : true,
      includeTitleTags: true,
      headingsOffset  : -boardTop,
    }, CONFIG.toc));
    if (toc.find('.toc-list-item').length > 0) {
      toc.css('visibility', 'visible');
    }

    Fluid.events.registerRefreshCallback(function() {
      if ('tocbot' in window) {
        tocbot.refresh();
        var toc = jQuery('#toc');
        if (toc.length === 0 || !tocbot) {
          return;
        }
        if (toc.find('.toc-list-item').length > 0) {
          toc.css('visibility', 'visible');
        }
      }
    });
  });
</script>


  <script src=https://lib.baomitu.com/clipboard.js/2.0.11/clipboard.min.js></script>

  <script>Fluid.plugins.codeWidget();</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/anchor-js/4.3.1/anchor.min.js', function() {
    window.anchors.options = {
      placement: CONFIG.anchorjs.placement,
      visible  : CONFIG.anchorjs.visible
    };
    if (CONFIG.anchorjs.icon) {
      window.anchors.options.icon = CONFIG.anchorjs.icon;
    }
    var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
    var res = [];
    for (var item of el) {
      res.push('.markdown-body > ' + item.trim());
    }
    if (CONFIG.anchorjs.placement === 'left') {
      window.anchors.options.class = 'anchorjs-link-left';
    }
    window.anchors.add(res.join(', '));

    Fluid.events.registerRefreshCallback(function() {
      if ('anchors' in window) {
        anchors.removeAll();
        var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
        var res = [];
        for (var item of el) {
          res.push('.markdown-body > ' + item.trim());
        }
        if (CONFIG.anchorjs.placement === 'left') {
          anchors.options.class = 'anchorjs-link-left';
        }
        anchors.add(res.join(', '));
      }
    });
  });
</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.js', function() {
    Fluid.plugins.fancyBox();
  });
</script>


  <script>Fluid.plugins.imageCaption();</script>

  <script  src="/js/local-search.js" ></script>

  <script defer src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js" ></script>




  
<script src="//cdn.jsdelivr.net/gh/bynotes/texiao/source/js/love.js"></script>
<script src="//cdn.jsdelivr.net/gh/bynotes/texiao/source/js/xiaoxingxing.js"></script>
<script src="//cdn.jsdelivr.net/gh/bynotes/texiao/source/js/xiaoxuehua.js"></script>
<script src="//cdn.jsdelivr.net/gh/bynotes/texiao/source/js/caidai.js"></script>



<!-- 主题的启动项，将它保持在最底部 -->
<!-- the boot of the theme, keep it at the bottom -->
<script  src="/js/boot.js" ></script>


  

  <noscript>
    <div class="noscript-warning">博客在允许 JavaScript 运行的环境下浏览效果更佳</div>
  </noscript>
</body>
</html>
